package org.amse.korovkin.ciphering.model.cipher.util;

import java.util.HashMap;

/**
 *
 * @author Mikhail Korovkin (maverick3089@yandex.ru)
 */
public class BinaryUtils {
    private static HashMap<Binary, Binary> pairs;
    private static Binary module;

    public static Binary getInverse(Binary b, Binary module) {
        if (pairs == null || !BinaryUtils.module.equals(module)) {
            BinaryUtils.module = module;
            initPairs(module);
        }
        if (pairs.get(b) == null) {
            System.out.println("ah ah ah! : " + b);
        }
        return pairs.get(b);
    }

    private static void initPairs(Binary module) {
        pairs = new HashMap<Binary, Binary>();
        pairs.put(new Binary(0), new Binary(0));
        Binary cur;
        for (int i = 1; i < module.getModule(); i++) {
            cur = new Binary(i);
            if (pairs.containsKey(cur)) {
                pairs.put(pairs.get(cur), cur);
            } else {
                Binary inverse;
                boolean found = false;
                for (int j = 1; j < module.getModule(); j++) {
                    inverse = new Binary(j);
                    if (cur.mult(inverse).mod(module).intValue() == 1) {
                        pairs.put(inverse, cur);
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    System.out.println("Can not find inverse for value: " + i);
                }
            }
        }
    }

    public static void main(String[] args) {
        BinaryUtils.getInverse(new Binary(3), new Binary(283));
        System.out.println(pairs);
    }
}
